package com.heima.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/20
 */
@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * app端登录
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        Map<String, Object> data = new HashMap<>();
        if (ObjectUtil.isEmpty(loginDto) ||
                StringUtils.isEmpty(loginDto.getPhone()) ||
                StringUtils.isEmpty(loginDto.getPassword())) {
            //游客登录：0
            data.put("token", AppJwtUtil.getToken(0L));
        } else {
            //正常登录：用户名+密码
            //根据手机号查询用户
            QueryWrapper<ApUser> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", loginDto.getPhone());
            ApUser apUser = this.getOne(wrapper);
            if (ObjectUtil.isEmpty(apUser)) {
                return ResponseResult.errorResult(
                        AppHttpCodeEnum.DATA_NOT_EXIST, "用户名或密码错误");
            }
            //比较密码是否一致
            String rightPassword = apUser.getPassword();
            String importPassword = MD5Utils.encodeWithSalt(loginDto.getPassword(), apUser.getSalt());
            if (!importPassword.equals(rightPassword)) {
                return ResponseResult.errorResult(
                        AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户名或密码错误");
            }
            //构造返回值的data，注意清空用户的密码相关信息
            apUser.setSalt("");
            apUser.setPassword("");
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId().toString()));
            data.put("user", apUser);
            data.put("token", token);
        }
        return ResponseResult.okResult(data);
    }
}
